package objects;

import helpers.DominoesSorter;
import helpers.GameThread;
import helpers.GamerThread;

import java.util.Arrays;
import java.util.List;
import java.util.StringTokenizer;
import java.util.Vector;

import objects.Player.Status;

public class DominoGame {

	public Vector<Domino> mexicanTrain;

	public Vector<Vector<Domino>> playerLines;

	public Vector<Player> players;

	private Vector<Domino> gameSet;

	private DominoesSorter dominoesSorter;

	private int setSize = 16;
        
        private int turno = 1;

	public DominoGame() {

		mexicanTrain = new Vector<Domino>();

		playerLines = new Vector<Vector<Domino>>();

		players = new Vector<Player>();

		gameSet = new Vector<Domino>();

		List<Domino> dominoes = Arrays.asList(Domino.values());
		this.gameSet.addAll(dominoes);

		setDominoesSorter(new DominoesSorter(players, gameSet));

		playerLines.add(mexicanTrain);

	}

	public Integer addPlayer(String player_name, GamerThread gamerThread) {
		int result = 0;
		if (this.players.size() <= 8) {
			Player newPlayer = new Player();
			Vector<Domino> playerLine = new Vector<Domino>();
			newPlayer.setName(player_name);
			newPlayer.setGameThread(gamerThread);
			this.players.add(newPlayer);
			this.playerLines.add(playerLine);
			int playernum = this.players.indexOf(newPlayer) + 1;
			result = playernum;
		} else {
			result = -1;
		}

		return result;
	}

	public void broadcastStartGame() {

		
	    GameThread dominoGameThread = new GameThread(this);
	    dominoGameThread.start();
		

	}

	public void move(Integer playerNumber, Integer lineNumber, String tuple) {

		int f = 1;
		int s = 2;
                 int i;
                    String tupla,numero;
                    StringTokenizer elementos,subelementos;
                    elementos = new StringTokenizer(tuple,"[]");
                    while(elementos.hasMoreTokens())
                    {
                      Integer [] ficha = new Integer [2];
                      tupla = elementos.nextToken();
                      i=0;
                      subelementos = new StringTokenizer(tupla,",");
                      while(subelementos.hasMoreTokens())
                      {
                        numero = subelementos.nextToken();
                        ficha[i] = Integer.valueOf(numero);
                        //System.out.println(i+". "+numero);
                        i++;
                      }                  
                      f = ficha[0];
                      s = ficha[1];
                    }
                    
                
		Domino move = Domino.findDomino(f, s);
		//boolean validMove;
		
		if (move != null) {
			Vector<Domino> playerSet = this.players.get(playerNumber-1)
					.getDominoSet();
			playerSet.remove(move);
			Vector<Domino> playerTrain = this.playerLines.get(lineNumber);
			//playerTrain.add(move);
			broadcastMove(playerNumber, lineNumber, f, s);
		}

	}
	
	public boolean validateMove(Domino domino, Vector<Domino> playerTrain, Vector<Domino> playerSet){
		boolean result = true;
		
		result = result & playerSet.contains(domino);
		Domino lastTile = playerTrain.lastElement();
		
		if((lastTile.getFirst()!= domino.getFirst())||(lastTile.getFirst()!= domino.getSecond())){
			
		}
		return result;
	}

	public void broadcastMove(Integer playerNumber, Integer lineNumber, int f,
			int s) {
                int env = 0, resp = 0;
                boolean again = false;
                
		for (Player p : this.players) {
			GamerThread gamerthread = p.getGameThread();
                    
			if (this.players.get(playerNumber-1) == p) {
                            System.out.println("turno: "+turno+" tam: "+players.size()+" playnumbre: "+playerNumber);
                            if(playerNumber == turno)
                            {
                                env=0;
                                resp = 0;
                                if(lineNumber == 0)
                                {
                                   resp = p.verifyMove(f, s, mexicanTrain);
                                    if(resp!=0)
                                    {
                                        if(resp==2)
                                        {
                                            Domino d = Domino.findDomino(s, f);
                                            mexicanTrain.add(d);
                                        }
                                        if(resp==1)
                                        {
                                            Domino d = Domino.findDomino(f, s);
                                            mexicanTrain.add(d);
                                        }
                                        if(f == s)
                                        {
                                            gamerthread.answer("moveagain");
                                            again=true;
                                        }
                                        else
                                            gamerthread.answer("moveok" + "_[" + f + "," + s + "]");
                                        for (Player p2 : this.players) {
                                                GamerThread gamerthread2 = p2.getGameThread();

                                                if (this.players.get(playerNumber-1) != p2) {
                                                   // if(env==0)
                                                        gamerthread2.answer("movegamer_" + lineNumber + "_[" + f + "," + s+ "]");
                                                }
                                            }                                            
                                        if(!again)
                                        {
                                            if(players.size()==turno)
                                            {
                                                turno = 1;
                                                System.out.println("en 0 turno: "+turno+" tam: "+players.size()+" again: "+again);
                                            }
                                            else
                                            {
                                                turno ++;
                                                System.out.println("en ++ turno: "+turno+" tam: "+players.size()+" again: "+again);
                                            }
                                        }
                                    }
                                    else
                                    {
                                        turno = playerNumber;
                                        gamerthread.answer("movewrong" + "_[" + f + "," + s + "]");
                                    } 
                                }
                                else
                                {
                                    resp = p.verifyMove(f, s, playerLines.get(lineNumber));
                                    if(resp!=0)
                                    {
                                        if(f == s)
                                        {
                                            gamerthread.answer("moveagain");
                                            again=true;
                                        }
                                        else
                                        {
                                            if(resp==2)
                                            {
                                                gamerthread.answer("moveok" + "_[" + s + "," + f + "]");
                                                Domino d = Domino.findDomino(f, s);                                                
                                                playerLines.get(lineNumber).add(d);
                                            }
                                            if(resp==1)
                                            {
                                                gamerthread.answer("moveok" + "_[" + f + "," + s + "]");
                                                Domino d = Domino.findDomino(f, s);
                                                playerLines.get(lineNumber).add(d);
                                            }
                                        }
                                        for (Player p2 : this.players) {
                                                GamerThread gamerthread2 = p2.getGameThread();

                                                if (this.players.get(playerNumber-1) != p2) {
                                                    //if(env==0)
                                                        gamerthread2.answer("movegamer_" + lineNumber + "_[" + f + "," + s+ "]");
                                                }
                                            }                                        
                                        if(!again)
                                        {
                                            if(players.size()==turno)
                                            {   
                                                turno = 1;
                                                System.out.println("en 0 turno: "+turno+" tam: "+players.size()+" again: "+again);
                                            }
                                            else
                                            {
                                                turno ++;
                                                System.out.println("en ++ turno: "+turno+" tam: "+players.size()+" again: "+again);
                                            }
                                        }
                                    }
                                    else
                                    {
                                        turno = playerNumber;
                                        gamerthread.answer("movewrong" + "_[" + f + "," + s + "]");
                                    }
                                }
                            }
			 else {
                               //moveturn
                                env = 1;
                                gamerthread.answer("moveturn");
			}                                                
                    }
		}
	}

	public void stealDomino(int playerNumber) {
		Player p = this.players.get(playerNumber-1);
		Vector<Domino> playerSet = p.getDominoSet();
		Domino toSteal = getDominoesSorter().getRandomDomino(playerSet, gameSet);
		playerSet.add(toSteal);
		GamerThread gamerthread = p.getGameThread();

		gamerthread.answer("ask_[" + toSteal.getFirst() + ","
				+ toSteal.getSecond() + "]");
	}

	public void setDominoesSorter(DominoesSorter dominoesSorter) {
		this.dominoesSorter = dominoesSorter;
	}

	public DominoesSorter getDominoesSorter() {
		return dominoesSorter;
	}

	public void setSetSize(int setSize) {
		this.setSize = setSize;
	}

	public int getSetSize() {
		return setSize;
	}

	public void passLine(int playerNumber) {
		Player p = this.players.get(playerNumber-1);
		Vector<Domino> playerSet = p.getDominoSet();
		GamerThread gamerthread = p.getGameThread();
		p.setStatus(Status.OPEN);
		gamerthread.answer("openline_"+playerNumber);
		
	}

}
